package com.rd.sys.servlet.auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.dto.commmon.base.EyeResult;

public class LoginCodeServlet extends AuthBaseServlet {
    private static final long serialVersionUID = 2445965020334389073L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doService(req, resp, true);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doService(req, resp, false);
    }

    protected void doService(HttpServletRequest req, HttpServletResponse resp, boolean isFromGet)
            throws ServletException, IOException {
        try {
            /* 从http请求中读取用户编码 */
            BufferedReader reader = null;
            String userCode = null;
            if (!isFromGet) {
                try {
                    reader = new BufferedReader(new InputStreamReader(req.getInputStream(),
                            CommonConstants.SysParamConstants.SYS_CHARSET));

                    userCode = reader.readLine();
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
            } else {
                userCode = req.getParameter("code");
            }

            /* 生成随机码 */
            String rand = RandomStringUtils.randomAlphanumeric(CommonConstants.UserConstats.AUTH_RAND_LENGTH);

            /* 放入Session中(为兼容客户端现放入缓存中,以随机码为key,用户编码为value) */
            // SessionUtil.getSession(req,
            // true).setAttribute(CommonConstants.UserConstats.AUTH_LOGIN_SESSION_FLAG,
            // usercode + CommonConstants.UserConstats.AUTH_SPLIT_SIGN + rand);
            this.putLoginCode(rand, userCode);

            /* 响应随机码 */
            logger.info("the response message is: usercode = " + userCode + " rand = " + rand);
            this.sendResponse(rand, resp);

        } catch (Exception ex) {
            logger.error("", ex);
            EyeResult result = new EyeResult(EyeResult.ResultDefine.COMMON_OTHER_ERROR_SERVER);
            sendResponse(result, req, resp);
        }
    }
}
